package com.runen.wnhz.runen.common.login.qq;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.runen.wnhz.runen.R;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

public class QQLoginActivity extends Activity {

    private Tencent mTencent;
    private Context mContext;
    private UserInfo mUserInfo;
    private QQCallBack mCallBack;

    public void close() {
        finish();
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN ||
                requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data, mLoginListener);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qq_login);

        this.mContext = QQLoginActivity.this;
        this.mCallBack = QQUtils.getInstance().getCallBack();
        this.mTencent = Tencent.createInstance(QQUtils.getInstance().getQQAppID(), getApplicationContext());

        if (!mTencent.isQQInstalled(mContext)) {
            Toast.makeText(mContext, "您还未安装QQ客户端", Toast.LENGTH_SHORT).show();
            close();
        } else {
            if (!mTencent.checkSessionValid(QQUtils.getInstance().getQQAppID())) {
                // token过期，请调用登录接口拉起手Q授权登录
                if (!mTencent.isSessionValid()) {
                    //如果session无效(未登录状态)，就开始登录
                    mTencent.login(this, "get_simple_userinfo", mLoginListener);
                } else {
                    //如果session有效(登录状态)
                }
            } else {
                // 使用token信息登录,不拉起手Q
                mTencent.initSessionCache(mTencent.loadSession(QQUtils.getInstance().getQQAppID()));
                updateUserInfo();
            }
        }
    }

    private IUiListener mLoginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            initOpenidAndToken(values);
            updateUserInfo();
        }
    };

    private void updateUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            mUserInfo = new UserInfo(mContext, mTencent.getQQToken());
            mUserInfo.getUserInfo(new IUiListener() {
                @Override
                public void onComplete(Object response) {
                    //nickname figureurl
                    JSONObject json = (JSONObject) response;
                    try {
                        String figureurl = json.getString("figureurl");
                        String nickname = json.getString("nickname");
                        if (mCallBack != null) {
                            mCallBack.saveUserInfo(nickname, figureurl);
                        }
                        close();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(UiError uiError) {
                    Toast.makeText(getApplication(), "获取用户信息失败", Toast.LENGTH_SHORT).show();
                    close();
                }

                @Override
                public void onCancel() {
                    Toast.makeText(getApplication(), "取消获取用户信息", Toast.LENGTH_SHORT).show();
                    close();
                }
            });
        }
    }

    public void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
                if (mCallBack != null) {
                    mCallBack.saveLoginInfo(token, openId);
                }
            }
        } catch (Exception e) {
        }
    }
/**
 *  QQ登录监听类*/
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                Toast.makeText(getApplication(), "登录信息丢失", Toast.LENGTH_SHORT).show();
                close();
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                Toast.makeText(getApplication(), "登录解析失败", Toast.LENGTH_SHORT).show();
                close();
                return;
            }

            try {
                int ret = jsonResponse.getInt("ret");
                if (ret == 0) {
                    doComplete((JSONObject) response);
                }
            } catch (Exception e) {
            }
        }

        protected void doComplete(JSONObject values) {

        }

        @Override
        public void onError(UiError e) {
            Toast.makeText(getApplication(), "登录错误:" + e.errorDetail, Toast.LENGTH_SHORT).show();
            close();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getApplication(), "登录取消", Toast.LENGTH_SHORT).show();
            close();
        }
    }
}
